package com.summer.wxapp.controller;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.summer.core.annotations.Logger;
import com.summer.core.util.FacesUtil;
import com.summer.wxapp.model.WeAppUser;
import com.summer.wxapp.service.WeAppUserService;
import com.summer.wxapp.util.WechatAppUtil;

/**
 * 微信用户信息接口控制器
 * @author	Summer
 * @Date	2018年1月24日
 *
 */
@Component
public class WeChatUserController {

	@Logger
	static Log log;
	
	@Resource
	WeAppUserService weAppUserService;
	
	public void loginByWechat() {
		
	}
	
	public void bindingWechat() {
		
	}
	
	public void authorizeWeChatUser() {
		HttpServletRequest request = FacesUtil.getHttpServletRequest();
		try {
			request.setCharacterEncoding("UTF-8");
			@SuppressWarnings("unchecked")
			Map<String, String[]> parameter = request.getParameterMap();// <String,String[]>
			String[] weUserId = parameter.get("weUserId");
			System.out.println(weUserId[0]);
			
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void getUserInfo() {
		HttpServletRequest request = FacesUtil.getHttpServletRequest();
		try {
			request.setCharacterEncoding("UTF-8");
			@SuppressWarnings("unchecked")
			Map<String, String[]> parameter = request.getParameterMap();// <String,String[]>
			String code = parameter.get("code")[0];
			String encryptedData = parameter.get("encryptedData")[0];
			String iv = parameter.get("iv")[0];
			
			JSONObject sessionKeyOropenid = WechatAppUtil.getSessionKeyOropenid(code);
			JSONObject json = WechatAppUtil.getUserInfo(encryptedData, sessionKeyOropenid.getString("session_key"), iv);
			System.out.println(json);
			List<WeAppUser> list = weAppUserService.queryWeAppUserListByOpenId(json.getString("openId"));
			
			if(null == list || list.size() == 0) {
				WeAppUser weAppUser = weAppUserService.createWeUserFromApp(json);
				weAppUser.setBindindTime(new Date());
//				weAppUser.set
				weAppUserService.saveWeUserFromApp(weAppUser);
			}
			
			WechatAppUtil.responseMsg("成功了");
			
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	 
	
}
